package com.foreknow.web;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.foreknow.entity.Department;
import com.foreknow.service.DepartmentService;
import com.foreknow.utils.Constance;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.foreknow.utils.downLoadExcel.downLoadExcel;

//科室管理
@RestController
@RequestMapping("/department")
public class DepartmentController {

    @Autowired
    private DepartmentService departmentService;

    //根据id 查询科室信息 参数 id
    @RequestMapping(value = "/findByDeptid",method = RequestMethod.POST)
    public String findByDeptid(@RequestBody Map<String,Object> para) throws JsonProcessingException {

        Integer id = (Integer) para.get("id");
        Department department = departmentService.selectByPrimaryKey(id);
        HashMap<String,Object> hs=new HashMap<>();
        ObjectMapper objectMapper=new ObjectMapper();
        //判断是否查询成功
        if(department!=null){
            hs.put("meta",new Constance("msg",200));
            hs.put("department",department);
        }else{
            hs.put("meta",new Constance("msg",404));
        }


        return objectMapper.writeValueAsString(hs);
    }



    //查询所有科室信息
    @RequestMapping(value = "/findAllDepartment",method = RequestMethod.POST)
    public String findAllDepartment(@RequestBody Map<String,Object> para) throws JsonProcessingException {

        List<Department> list = departmentService.selectAllDepartment();
        HashMap<String,Object> hs=new HashMap<>();
        ObjectMapper objectMapper=new ObjectMapper();
        //判断是否查询成功
        if(list.size()>0){
            hs.put("meta",new Constance("msg",200));
            hs.put("list",list);
        }else{
            hs.put("meta",new Constance("msg",404));
        }

        return objectMapper.writeValueAsString(hs);
    }

    //根据条件查询所有科室信息 参数 deptType
    @RequestMapping(value = "/findAllDepartmentByCondition",method = RequestMethod.POST)
    public String findAllDepartmentByCondition(@RequestBody Map<String,Object> para) throws JsonProcessingException {

        Integer id = (Integer) para.get("id");
        List<Department> list = departmentService.selectAllDepartmentByCondition(id);
        HashMap<String,Object> hs=new HashMap<>();
        ObjectMapper objectMapper=new ObjectMapper();
        //判断是否查询成功
        if(list.size()>0){
            hs.put("meta",new Constance("msg",200));
            hs.put("list",list);
        }else{
            hs.put("meta",new Constance("msg",404));
        }

        return objectMapper.writeValueAsString(hs);
    }


    //查询所有科室信息，用于初始化列表展示
    @ApiOperation("查询所有科室信息，用于初始化列表展示")
    @RequestMapping(value = "/queryDeptName",method = RequestMethod.GET)
    public String queryDeptName(@RequestParam Map<String,Object> para) throws JsonProcessingException {
        HashMap<String,Object> hs =new HashMap();
        Integer pageNum =Integer.parseInt((String) para.get("pageNum"));
        Integer pageSize =Integer.parseInt((String)  para.get("pageSize"));
        //设置分页信息
        PageHelper.startPage(pageNum,pageSize);
        List list = departmentService.queryDeptName();
        //PageInfo是PageHelper中内置的分页信息类
        PageInfo<Department> info = new PageInfo(list);
        //给map添加数据
        hs.put("total",info.getTotal());
        hs.put("pageNum",info.getPageNum());
        hs.put("list",list);
        if (list.size()>0){
            hs.put("meta",new Constance("获取科室列表成功",200));
        }else {
            hs.put("meta",new Constance("获取科室列表失败",401));
        }
        ObjectMapper objectMapper =new ObjectMapper();
        return objectMapper.writeValueAsString(hs);
    }

    //查询Constantitem所有科室分类信息，用于选择器展示
    @ApiOperation("查询Constantitem所有科室分类信息，用于选择器展示")
    @RequestMapping(value = "/queryItem",method = RequestMethod.GET)
    public String queryItem(@RequestParam Map<String,Object> para) throws JsonProcessingException {
        HashMap<String,Object> hs =new HashMap();
        Integer constanttypeid =Integer.parseInt((String) para.get("constanttypeid"));
        List list = departmentService.queryItem(constanttypeid);
        //给map添加数据
        hs.put("list",list);
        if (list.size()>0){
            hs.put("meta",new Constance("获取科室分类成功",200));
        }else {
            hs.put("meta",new Constance("获取科室分类失败",401));
        }
        ObjectMapper objectMapper =new ObjectMapper();
        return objectMapper.writeValueAsString(hs);
    }

    //添加科室信息
    @ApiOperation("添加科室信息")
    @RequestMapping(value = "insertDept",method = RequestMethod.POST)
    @ResponseBody
    public String insertDept(@RequestBody Map<String,Object> para) throws JsonProcessingException {
        //获取表单信息
        HashMap<String,Object> hs = new HashMap<>();
        String deptCode = (String) para.get("deptcode");
        String deptName = (String) para.get("deptname");
        Integer deptCategoryID  = (Integer) para.get("deptcategoryid");
        Integer deptType  = Integer.parseInt((String) para.get("depttype"));
        //传入Dep对象
        Department department =new Department();
        department.setDelmark(1);
        department.setDeptcode(deptCode);
        department.setDeptname(deptName);
        department.setDeptcategoryid(deptCategoryID);
        department.setDepttype(deptType);
        int isRight = departmentService.insertDep(department);
        if(isRight==1){
            hs.put("meta",new Constance("添加科室成功",200));
        }else {
            hs.put("meta",new Constance("添加科室失败",401));
        }
        ObjectMapper objectMapper =new ObjectMapper();
        return objectMapper.writeValueAsString(hs);
    }

    //通过id查询科室信息，用于更新前数据回显
    @ApiOperation("通过id查询科室信息，用于更新前数据回显")
    @RequestMapping(value = "selectDeptById",method = RequestMethod.GET)
    public String selectDeptById(@RequestParam Map<String,Object>para) throws JsonProcessingException {
        //获取表单信息
        HashMap<String,Object> hs = new HashMap<>();
        Integer id =Integer.parseInt((String) para.get("id"));
        Department department = departmentService.seletById(id);
        hs.put("department",department);
        if (department!=null){
            hs.put("meta",new Constance("根据id获取科室信息成功",200));
        }else {
            hs.put("meta",new Constance("根据id获取科室信息失败",401));
        }
        ObjectMapper objectMapper = new ObjectMapper();
        return  objectMapper.writeValueAsString(hs);
    }

    //根据id修改科室信息
    @ApiOperation("根据id修改科室信息")
    @RequestMapping(value = "updateDept" ,method = RequestMethod.POST)
    public String updateDeptById(@RequestBody Map<String,Object> para) throws JsonProcessingException {
        //获取表单信息
        HashMap<String,Object> hs = new HashMap<>();
        String deptCode = (String) para.get("deptcode");
        String deptName = (String) para.get("deptname");
        Integer deptCategoryID  = (Integer) para.get("deptcategoryid");
        Integer deptType  = Integer.parseInt((String) para.get("depttype"));
        Integer depID  = Integer.parseInt((String) para.get("id"));
        Department department =new Department();
        department.setDelmark(1);
        department.setId(depID);
        department.setDeptcode(deptCode);
        department.setDeptname(deptName);
        department.setDeptcategoryid(deptCategoryID);
        department.setDepttype(deptType);
        //调用service修改方法
        int isRight = departmentService.updateDep(department);
        if (isRight==1){
            hs.put("meta",new Constance("修改科室成功",200));
        }else {
            hs.put("meta",new Constance("修改科室失败",401));
        }
        ObjectMapper objectMapper = new ObjectMapper();
        return  objectMapper.writeValueAsString(hs);
    }

    //根据条件查询科室信息
    @ApiOperation("根据条件查询科室信息")
    @RequestMapping(value = "queryDept",method = RequestMethod.POST)
    @ResponseBody
    public String queryDept(@RequestBody Map<String,Object> para) throws JsonProcessingException{
        HashMap<String,Object> hs=new HashMap<>();
        //获取请求参数
        Integer pageNum =Integer.parseInt((String) para.get("pageNum"));
        Integer pageSize =Integer.parseInt((String)  para.get("pageSize"));
        String deptCode = (String) para.get("deptcode");
        String deptName = (String) para.get("deptname");
        Integer deptCategoryID=null;
        Integer deptType  =null;
        if(para.get("deptcategoryid")!=null&&para.get("deptcategoryid")!=""){
            deptCategoryID  =(Integer) para.get("deptcategoryid");
        }
        if(para.get("depttype")!=null&&para.get("depttype")!=""){
            deptType  = Integer.parseInt((String) para.get("depttype"));
        }
        Department department =new Department();
        department.setDeptcode(deptCode);
        department.setDeptname(deptName);
        department.setDeptcategoryid(deptCategoryID);
        department.setDepttype(deptType);
        department.setDelmark(1);
        PageHelper.startPage(pageNum,pageSize);
        List<Department> depList = departmentService.selectByWhere(department);
        PageInfo<Department> info = new PageInfo(depList);
        hs.put("department",depList);
        hs.put("total",info.getTotal());
        hs.put("pageNum",info.getPageNum());
        //添加meta
        if (depList.size()>=0){
            hs.put("meta",new Constance("根据条件获取科室信息成功",200));
        }else {
            hs.put("meta",new Constance("根据条件获取科室信息失败",401));
        }
        ObjectMapper objectMapper =new ObjectMapper();
        return objectMapper.writeValueAsString(hs);
    }

    //根据id删除科室信息
    @ApiOperation("根据id删除科室信息")
    @RequestMapping(value = "deleteDepById" ,method = RequestMethod.GET)
    public String deleteDeptById(@RequestParam Map<String,Object>para) throws JsonProcessingException {
        HashMap<String,Object> hs=new HashMap<>();
        Integer id = Integer.parseInt((String)para.get("id"));
        int isRight = departmentService.deleteDepById(id);
        if (isRight==1){
            hs.put("meta",new Constance("删除科室成功",200));
        }else {
            hs.put("meta",new Constance("删除科室失败",401));
        }
        ObjectMapper objectMapper =new ObjectMapper();
        return objectMapper.writeValueAsString(hs);
    }

    //批量删除科室信息
    @ApiOperation("批量删除科室信息")
    @RequestMapping(value = "deleteByChoose",method = RequestMethod.POST)
    public String deleteByChoose(@RequestBody Map<String ,Object> para) throws JsonProcessingException {
        HashMap<String,Object> hs=new HashMap<>();
        List<Integer> arr = new ArrayList<Integer>();;
        arr= (List<Integer>) para.get("info");

        int sum =0;
        int isRight =0;
        for(Integer ss:arr
        ) {
            isRight = departmentService.deleteDepById(ss);
            sum = sum + isRight;
        }
        if (sum==arr.size()){
            hs.put("meta",new Constance("批量删除科室成功",200));
        }else {
            hs.put("meta",new Constance("批量删除科室失败",401));
        }
        ObjectMapper objectMapper =new ObjectMapper();
        return objectMapper.writeValueAsString(hs);
    }

    //从文件批量上传科室信息
    @ApiOperation("从文件批量上传科室信息")
    @RequestMapping(value = "/ExcelInsertDept", method = RequestMethod.POST)
    @ResponseBody
    public String ExcelInsertDept(@RequestParam("excelFile") MultipartFile excelFile) throws JsonProcessingException {
        String name = excelFile.getOriginalFilename();
        ObjectMapper objectMapper =new ObjectMapper();
        HashMap<String,Object> hs=new HashMap<>();
        try {
            if(departmentService.excelToList(excelFile.getInputStream())>0) {
                hs.put("meta",new Constance("批量添加成功",200));
                return objectMapper.writeValueAsString(hs);
            }else {
                hs.put("meta",new Constance("批量添加失败",401));
                return objectMapper.writeValueAsString(hs);
            }
        } catch (Exception e) {
            e.printStackTrace();
            hs.put("meta",new Constance("批量添加失败",401));
            return objectMapper.writeValueAsString(hs);
        }
    }

    @ApiOperation("从前端下载数据模版")
    @RequestMapping(value="/downloadExcel", method = RequestMethod.POST)
    public ResponseEntity<Resource> excel2007Export(HttpServletResponse response, HttpServletRequest request) {
        try {
            ClassPathResource cpr = new ClassPathResource("/templates/" + "Department.xlsx");
            InputStream is = cpr.getInputStream();
            Workbook workbook = new XSSFWorkbook(is);
            String fileName = "Department.xlsx";
            downLoadExcel(fileName, response, workbook);

        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return new ResponseEntity<Resource>(HttpStatus.OK);
    }
}
